public class RemoveNthFromEnd {
    //leetcode 删除链表的倒数第N个节点
    // https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/?envType=study-plan-v2&envId=top-100-liked
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode fast = head, prev = head;
        for (int i = 0; i < n-1; i++) {
            prev = fast;
            fast = fast.next;
        }
        // 说明要删除头节点
        if (fast.next == null) {
            return head.next;
        }
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            prev = slow;
            slow = slow.next;
            fast = fast.next;
        }
        prev.next = prev.next.next;
        return head;
    }
}
